const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const tool = require("../../tools/tool");
const router = new Router();

router.post('/app/saveGood', async ctx => {
    let formData = ctx.request.body.formData
    let tenantId = ctx.user.tenantId
    let goodModel = null;
    if(formData.name.indexOf('[') !== -1) return ctx.err('不能包含字符[')
    if(formData.name.indexOf(']') !== -1) return ctx.err('不能包含字符]')
    if(formData.id) {
        let has = await db.models['goods'].findOne({
            where: {
                tenantId,
                name: formData.name,
                id: {
                    [Op.ne]: formData.id
                }
            }
        })
        if(has) {
            return  ctx.err('已存在相同名称')
        }
        goodModel = await db.models['goods'].findOne({
            where: {
                id: formData.id,
                tenantId
            }
        })
        let hasDetail = await db.models['invoiceInfo'].findOne({
            where: {
                tenantId,
                invId: formData.id
            }
        })
        if(hasDetail) {
            if (tool.xe.toNumber(goodModel.spec) !== tool.xe.toNumber(formData.spec)) {
                return  ctx.err('已使用商品，不能修改规格')
            }
        }
        goodModel.barCode = formData.barCode
        goodModel.barCode1 = formData.barCode1
        goodModel.pinYin = tool.py(formData.name)
        goodModel.categoryId = formData.categoryId
        goodModel.name = formData.name
        goodModel.spec = formData.spec
        goodModel.unit1 = formData.unit1
        goodModel.unit2 = formData.unit2
        goodModel.price1 = formData.price1
        goodModel.price2 = formData.price2
        await goodModel.save()
    }
    else {
        let has = await db.models['goods'].count({
            where: {
                tenantId,
                name: formData.name
            }
        })
        if(has > 0) {
            return  ctx.err('已存在相同名称')
        }
        goodModel = db.models['goods'].build();
        goodModel.tenantId = tenantId
        goodModel.barCode = formData.barCode
        goodModel.barCode1 = formData.barCode1
        goodModel.pinYin = tool.py(formData.name)
        goodModel.categoryId = formData.categoryId
        goodModel.name = formData.name
        goodModel.spec = formData.spec
        goodModel.unit1 = formData.unit1
        goodModel.unit2 = formData.unit2
        goodModel.price1 = formData.price1
        goodModel.price2 = formData.price2
        await goodModel.save()
    }
    return ctx.suc('保存成功')
})


module.exports = router;
